package cxl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Search {

	private List<File> fileList;
	private List<String> equalsList;

	public static void main(String arg[]) {
		if (arg != null) {
			Search ts = new Search();
			ts.run();

		}
	}
	public Search() {
		fileList = new ArrayList<File>();
		equalsList = new ArrayList<String>();
	}

	private void run(){
		Scanner s = new Scanner(System.in);
		while(true){
			System.out.println("enter file or directory:");
			String path = s.nextLine();
			while(true){
				System.out.println("enter key:");
				String str = s.nextLine();
				if("c".equals(path))
					break;
				
				StringBuffer sb = new StringBuffer(path);
				sb.insert(2, '\\');
				String filePath = sb.toString();
				File file = new File(filePath);
				findFile(file);
				for (int i = 0; i < fileList.size(); i++) {
					search(fileList.get(i), str);
				}
				print();
				clear();
			}
		}


	}
	
	private void clear(){
		fileList.clear();
		equalsList.clear();
	}
	
	private void findFile(File file) {
		if (file.isDirectory()) {
			File[] fileGroup = file.listFiles();
			for (int j = 0; j < fileGroup.length; j++) {
				findFile(fileGroup[j]);
			}
		} else {
//			 System.out.println(file.getPath());
//			fileList.add(file);
			StringBuffer sb1 = new StringBuffer(file.getPath());
			int start = sb1.lastIndexOf(".");
			String type = sb1.substring(start + 1);
			if("java".equals(type)){
				fileList.add(file);
			}

		}
	}

	private void print() {
		System.out.println("----------------------------------------------------------------------------");
		if(equalsList.size() == 0)
			System.out.println("null");
		else
			System.out.println("The following files contain keywords:");

		for(int i = 0; i < equalsList.size(); i++){
			System.out.println(equalsList.get(i));
		}
		System.out.println("----------------------------------------------------------------------------");
	}

	private void search(File file ,String str){
		InputStream is = null;
		try {
			is = new FileInputStream(file);
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String temp = null;
			while((temp = br.readLine()) != null){
				if(temp.indexOf(str) != -1){
					equalsList.add(file.getAbsolutePath());
					break;
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}
	
}
